package com.example.auth.uitls;

import com.example.auth.model.UserModel;

import java.util.*;

/**
 * @Classname UserModelMap
 * @Description TODO
 * @Date 2022/7/27 19:32
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class UserModelMap {

    private static Map<String, UserModel> modelMap;

    private static void init(){
        if(UserModelMap.modelMap == null){
            UserModelMap.modelMap = new HashMap<>(1000);
        }
    }

    public static UserModel getUserModel(String token){
        init();
        if(modelMap.containsKey(token)){
            UserModel userModel=modelMap.get(token);
            if(userModel.getExpiredate()!=null){
                Date now=new Date();
                if(now.getTime() > userModel.getExpiredate().getTime()){
                    modelMap.remove(token,userModel);
                    return null;
                }
            }
            return userModel;
        }
        return null;
    }

    public static void putUserModel(String token,UserModel userModel){
        init();
        //清空其他的token
        removeTokenByUserName(userModel.getUsername());
        Date expireDate=getExpireDate();
        userModel.setExpiredate(expireDate);
        modelMap.put(token,userModel);
    }


    /**
     * 下线用户
     * @param username
     */
    public static void removeTokenByUserName(String username){
        if(UserModelMap.modelMap==null){
            return;
        }
        Map<String,UserModel> map=UserModelMap.modelMap;
        for (Map.Entry<String,UserModel> entry : map.entrySet()){
            String token=entry.getKey();
            UserModel userModel = entry.getValue();
            String userName=userModel.getUsername();
            if(userName!=null){
                if(userName.equals(username)){
                    UserModelMap.modelMap.remove(token);
                }
            }
        }
    }

    /**
     * 获取所有的在线用户
     */
    public static List<UserModel> getOnlineUserModels(){
        init();
        List<UserModel> userModels = new ArrayList<>();
        Map<String, UserModel> map = UserModelMap.modelMap;
        for (Map.Entry<String,UserModel> userModel:map.entrySet()){
            UserModel user=userModel.getValue();
            userModels.add(user);
        }
        return userModels;
    }

    private static Date getExpireDate(){
        Calendar cal = Calendar.getInstance();
        Integer secord=30 * 60 * 1000;
        cal.add(Calendar.SECOND,secord);
        return cal.getTime();
    }


}
